package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class LoginInterceptor implements HandlerInterceptor {

//    private StringRedisTemplate stringRedisTemplate;

//    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
//        this.stringRedisTemplate = stringRedisTemplate;
//    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 token
//        String token = request.getHeader("authorization");
//        if(StrUtil.isBlank(token)){
//            response.setStatus(401);
//            return false;
//        }; // 校验 token 是否为空
//        String key = "login:token:" + token;
//        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(key);
//        if(userMap.isEmpty()){
//            response.setStatus(401);
//            return false;
//        }
//        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
//        // 刷新用户的过期时间
//        stringRedisTemplate.expire(key, 30, TimeUnit.MINUTES);
//        UserHolder.saveUser(userDTO);
        /*HttpSession session = request.getSession();
        Object loginUser = session.getAttribute("user");
        if (loginUser == null) {
            response.setStatus(401);
            return false;
        }
        UserHolder.saveUser((UserDTO) loginUser);*/
     //   System.out.println("====loginInterceptor当前登录用户：" + UserHolder.getUser());

        if(UserHolder.getUser() == null){
            response.setStatus(401);
            return false;
        }
        // 有用户放行
        return true;
    }

//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserHolder.removeUser();
//    }
}
